using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceProcess;
using Microsoft.Vsts.Ranger.Migration.TfsToTfs.Service.Services;

namespace TfsMigrationWindowsServiceHost
{
    public partial class TfsMigrationWindowsServiceHost : ServiceBase
    {
        ServiceHost host;
        MigrationService client;


        public TfsMigrationWindowsServiceHost()
        {
            InitializeComponent();

            this.AutoLog = false;

            
        }

        protected override void OnStart(string[] args)
        {
            System.Diagnostics.EventLog log = this.EventLog;

            try
            {
                log.Source = "Application";

                log.WriteEntry("TfsToTfs Migration Services starting...", EventLogEntryType.Information, 0, 0);

                //host = new ServiceHost(typeof (MigrationService));
                //host.Faulted += new EventHandler(host_Faulted);
                //host.Open();


                client = new MigrationService();
                client.InitializeService();

                log.WriteEntry("TfsToTfs Migration Services is up and ready to receive requests.",
                                             EventLogEntryType.Information, 0, 0);
                
            }
            catch(Exception ex)
            {
                log.WriteEntry("TfsToTfs Migration Services has faulted." + ex.Message, EventLogEntryType.Error, 0, 0);
            }



        }


        void host_Faulted(object sender, EventArgs e)
        {
            this.EventLog.WriteEntry("TfsToTfs Migration Services has faulted.", EventLogEntryType.Error, 0, 0);
        }

        protected override void OnStop()
        {
            try
            {
                this.EventLog.WriteEntry("TfsToTfs Migration Services is shutting down.", EventLogEntryType.Information,
                                         0, 0);

                
                client.ShutDownService();


                if (host != null)
                {
                    host.Close();
                    this.EventLog.WriteEntry("TfsToTfs Migration Services has been closed.",
                                             EventLogEntryType.Information,
                                             0, 0);
                }
            }
            catch
            {
            }
            finally
            {
                host = null;
            }

        }
    }
}